<template>
  <div class="chat-example-container">
    <div class="example-header">
      <h2 class="text-2xl font-bold text-gray-800 mb-4">ChatMessage 组件完整示例</h2>
      <p class="text-gray-600 mb-6">
        演示聊天消息组件的所有功能，包括文件显示、<strong>直接反馈系统</strong>、流式消息等。
        点赞/踩一踩按钮会直接调用反馈接口，无需额外表单。
      </p>
    </div>

    <!-- 控制面板 -->
    <div class="control-panel">
      <h3 class="text-lg font-semibold mb-3">控制面板</h3>
      <div class="control-buttons">
        <button @click="addUserMessage" class="btn btn-primary">
          添加用户消息
        </button>
        <button @click="addAIMessage" class="btn btn-secondary">
          添加AI消息
        </button>
        <button @click="addStreamingMessage" class="btn btn-accent">
          模拟流式消息
        </button>
        <button @click="addMessageWithFiles" class="btn btn-success">
          添加带文件的消息
        </button>
        <button @click="clearMessages" class="btn btn-danger">
          清空消息
        </button>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-area">
      <div class="chat-messages">
        <div v-if="messages.length === 0" class="empty-state">
          <p class="text-gray-500 text-center py-8">
            暂无消息，点击上方按钮开始对话
          </p>
        </div>
        
        <ChatMessage
          v-for="message in messages"
          :key="message.id"
          :message="message"
          :feedback-disabled="false"
          @copy="handleCopy"
          @regenerate="handleRegenerate"
          @feedback="handleFeedback"
          @suggest-question="handleSuggestQuestion"
        />
      </div>
    </div>

    <!-- 事件日志 -->
    <div class="event-log">
      <h3 class="text-lg font-semibold mb-3">事件日志</h3>
      <div class="log-content">
        <div v-if="eventLogs.length === 0" class="text-gray-500 text-sm">
          暂无事件记录
        </div>
        <div 
          v-for="(log, index) in eventLogs" 
          :key="index"
          class="log-item"
        >
          <span class="log-time">{{ formatLogTime(log.timestamp) }}</span>
          <span class="log-type" :class="getLogTypeClass(log.type)">
            {{ log.type }}
          </span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import ChatMessage from '@/components/chat/ChatMessage.vue'
import type { ChatItem, Feedbacktype } from '@/types/app'

// 扩展ChatItem类型以支持files属性
interface ExtendedChatItem extends ChatItem {
  files?: Array<{
    id: string
    name: string
    type: string
    size: number
    url: string
  }>
}

// 状态管理
const messages = ref<ExtendedChatItem[]>([])
const eventLogs = ref<Array<{
  timestamp: number
  type: string
  message: string
}>>([])

// 流式消息状态
const streamingMessage = ref<ExtendedChatItem | null>(null)
const streamingInterval = ref<NodeJS.Timeout | null>(null)

// 添加日志的辅助函数
const addLog = (type: string, message: string) => {
  eventLogs.value.unshift({
    timestamp: Date.now(),
    type,
    message
  })
  
  // 限制日志数量
  if (eventLogs.value.length > 50) {
    eventLogs.value = eventLogs.value.slice(0, 50)
  }
}

// 生成唯一ID
const generateId = () => `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

// 添加用户消息
const addUserMessage = () => {
  const userMessages = [
    "你好，我想了解一下人工智能的发展历史。",
    "请帮我分析一下这个数据报告。",
    "能否为我生成一个项目计划？",
    "我需要一些关于机器学习的资料。"
  ]
  
  const randomMessage = userMessages[Math.floor(Math.random() * userMessages.length)]
  
  const message: ExtendedChatItem = {
    id: generateId(),
    content: randomMessage,
    isAnswer: false,
    message_files: [],
    agent_thoughts: []
  }
  
  messages.value.push(message)
  addLog('USER_MESSAGE', `添加用户消息: ${randomMessage.substring(0, 30)}...`)
}

// 添加AI消息
const addAIMessage = () => {
  const aiResponses = [
    "人工智能的发展可以追溯到20世纪50年代，当时艾伦·图灵提出了著名的**图灵测试**。\n\n主要发展阶段包括：\n- 1950s-1960s: 符号主义AI的兴起\n- 1980s: 专家系统的发展\n- 1990s-2000s: 机器学习的突破\n- 2010s至今: 深度学习革命",
    "根据您提供的数据报告，我发现了以下几个关键趋势：\n\n1. **增长趋势**: 整体呈现上升态势\n2. **季节性变化**: 存在明显的周期性波动\n3. **异常值**: 在第三季度出现了显著的峰值\n\n建议进一步分析异常值的成因。",
    "我为您制定了一个详细的项目计划：\n\n## 项目阶段\n\n### 第一阶段：需求分析（2周）\n- 收集用户需求\n- 技术可行性评估\n\n### 第二阶段：设计开发（6周）\n- 系统架构设计\n- 核心功能开发\n\n### 第三阶段：测试部署（2周）\n- 功能测试\n- 性能优化"
  ]
  
  const randomResponse = aiResponses[Math.floor(Math.random() * aiResponses.length)]
  
  const message: ExtendedChatItem = {
    id: generateId(),
    content: randomResponse,
    isAnswer: true,
    message_files: [],
    agent_thoughts: [],
    feedback: undefined
  }
  
  messages.value.push(message)
  addLog('AI_MESSAGE', `添加AI消息: ${randomResponse.substring(0, 30)}...`)
}

// 模拟流式消息
const addStreamingMessage = () => {
  if (streamingInterval.value) {
    clearInterval(streamingInterval.value)
  }
  
  const fullContent = "这是一个模拟的流式消息示例。我将逐字逐句地显示内容，就像真实的AI对话一样。\n\n**流式传输的优势：**\n- 提供实时反馈\n- 改善用户体验\n- 减少等待时间\n\n让我们看看这个效果如何！"
  
  const message: ExtendedChatItem = {
    id: generateId(),
    content: '',
    isAnswer: true,
    message_files: [],
    agent_thoughts: [],
    streaming: true,
    feedback: undefined
  }
  
  messages.value.push(message)
  streamingMessage.value = message
  
  let currentIndex = 0
  const streamingSpeed = 50 // 毫秒
  
  streamingInterval.value = setInterval(() => {
    if (currentIndex < fullContent.length) {
      message.content = fullContent.substring(0, currentIndex + 1)
      currentIndex++
    } else {
      // 流式传输完成
      message.streaming = false
      streamingMessage.value = null
      clearInterval(streamingInterval.value!)
      streamingInterval.value = null
      addLog('STREAMING_COMPLETE', '流式消息传输完成')
    }
  }, streamingSpeed)
  
  addLog('STREAMING_START', '开始流式消息传输')
}

// 添加带文件的消息
const addMessageWithFiles = () => {
  const message: ExtendedChatItem = {
    id: generateId(),
    content: "我已经为您准备了相关的文档和资料。请查看以下文件：",
    isAnswer: true,
    message_files: [],
    agent_thoughts: [],
    feedback: undefined,
    files: [
      {
        id: 'report_2024.pdf',
        name: '2024年度分析报告.pdf',
        type: 'application/pdf',
        size: 2048576, // 2MB
        url: 'https://example.com/files/report_2024.pdf'
      },
      {
        id: 'chart_data.png',
        name: '数据图表.png',
        type: 'image/png',
        size: 512000, // 500KB
        url: 'https://picsum.photos/400/300?random=1'
      },
      {
        id: 'summary.docx',
        name: '项目总结.docx',
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        size: 1024000, // 1MB
        url: 'https://example.com/files/summary.docx'
      }
    ]
  }
  
  messages.value.push(message)
  addLog('MESSAGE_WITH_FILES', `添加带文件的消息，包含 ${message.files?.length} 个文件`)
}

// 清空消息
const clearMessages = () => {
  messages.value = []
  if (streamingInterval.value) {
    clearInterval(streamingInterval.value)
    streamingInterval.value = null
  }
  streamingMessage.value = null
  addLog('CLEAR_MESSAGES', '清空所有消息')
}

// 事件处理函数
const handleCopy = (content: string) => {
  addLog('COPY', `复制消息内容: ${content.substring(0, 30)}...`)
}

const handleRegenerate = (messageId: string) => {
  addLog('REGENERATE', `请求重新生成消息: ${messageId}`)
  // 这里可以实现重新生成逻辑
}

const handleFeedback = (messageId: string, feedback: Feedbacktype) => {
  // 更新消息的反馈
  const message = messages.value.find(m => m.id === messageId)
  if (message) {
    message.feedback = feedback
    addLog('FEEDBACK', `收到反馈: ${feedback.rating} - ${feedback.content || '无评论'}`)
  }
}

const handleSuggestQuestion = (question: string) => {
  addLog('SUGGEST_QUESTION', `建议问题被点击: ${question}`)
  // 这里可以实现自动发送建议问题的逻辑
}

// 辅助函数
const formatLogTime = (timestamp: number): string => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getLogTypeClass = (type: string): string => {
  const classes: Record<string, string> = {
    'USER_MESSAGE': 'text-blue-600',
    'AI_MESSAGE': 'text-green-600',
    'STREAMING_START': 'text-purple-600',
    'STREAMING_COMPLETE': 'text-purple-800',
    'MESSAGE_WITH_FILES': 'text-orange-600',
    'COPY': 'text-gray-600',
    'REGENERATE': 'text-yellow-600',
    'FEEDBACK': 'text-pink-600',
    'SUGGEST_QUESTION': 'text-indigo-600',
    'CLEAR_MESSAGES': 'text-red-600'
  }
  return classes[type] || 'text-gray-500'
}
</script>

<style scoped>
.chat-example-container {
  @apply max-w-4xl mx-auto p-6 space-y-6;
}

.example-header {
  @apply text-center;
}

.control-panel {
  @apply bg-white p-4 rounded-lg border border-gray-200 shadow-sm;
}

.control-buttons {
  @apply flex flex-wrap gap-2;
}

.btn {
  @apply px-4 py-2 rounded-lg font-medium transition-colors;
}

.btn-primary {
  @apply bg-blue-500 text-white hover:bg-blue-600;
}

.btn-secondary {
  @apply bg-gray-500 text-white hover:bg-gray-600;
}

.btn-accent {
  @apply bg-purple-500 text-white hover:bg-purple-600;
}

.btn-success {
  @apply bg-green-500 text-white hover:bg-green-600;
}

.btn-danger {
  @apply bg-red-500 text-white hover:bg-red-600;
}

.chat-area {
  @apply bg-white rounded-lg border border-gray-200 shadow-sm;
}

.chat-messages {
  @apply max-h-96 overflow-y-auto;
}

.empty-state {
  @apply p-8;
}

.event-log {
  @apply bg-gray-50 p-4 rounded-lg border border-gray-200;
}

.log-content {
  @apply max-h-48 overflow-y-auto space-y-1;
}

.log-item {
  @apply flex items-center gap-2 text-sm py-1;
}

.log-time {
  @apply text-gray-500 font-mono text-xs;
}

.log-type {
  @apply font-medium px-2 py-0.5 rounded text-xs;
}

.log-message {
  @apply text-gray-700;
}
</style> 